package com.crm.service.productionService;


import com.crm.dao.productionDAO.ProductionCategoryDAO;
import com.crm.dao.productionDAO.ProductionDetilsDAO;
import com.crm.pojo.ProductionDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class )
public class ProductionDetilsService {
    @Autowired
    private ProductionDetilsDAO productionDetilsDAO;
    @Autowired
    private ProductionCategoryDAO productionCategoryDAO;

    //1.查看所有的产品明细(未分页)
    public List<ProductionDetail> allProductions(){
        return (List<ProductionDetail>) productionDetilsDAO.findAll();
    }
    //2.分页查看所有的产品信息
    public List<ProductionDetail> allProductionsPaged(int curPage, int pageSize){
        PageRequest page  = new PageRequest(curPage-1,pageSize);
        List<ProductionDetail> productionDetails = productionDetilsDAO.queryByPage(page);
        for (ProductionDetail p:productionDetails) {
            if(p.getPcategory()!=null) {
                p.setpCategoryname(productionCategoryDAO.findOne(p.getPcategory()).getPcname());
            }
        }
        return productionDetails;
    }
    //3.查看总记录数
    public Long queryCount(){
        return productionDetilsDAO.queryCount();
    }
    //添加产品
    public void addPro(ProductionDetail productionDetail){
        productionDetilsDAO.save(productionDetail);
    }
    //修改产品信息
    public void updateProduction(ProductionDetail productionDetail){
        productionDetilsDAO.save(productionDetail);
    }
    //删除产品信息（逻辑删除）
    public void deleteproduction(ProductionDetail productionDetail){
        productionDetail.setProductionDetailsIsDel("已删除");
        productionDetilsDAO.save(productionDetail);
    }
    //根据id查询分类
    public ProductionDetail queryOneById(Long pid){
        return productionDetilsDAO.findOne(pid);
    }
    //根据产品名称或者产品id模糊查询，不查询删除的
    //1.查询全部
    public List<ProductionDetail> queryBypidOrpnameMh1(String q){
        return productionDetilsDAO.queryBypidOrpnameMh1("%"+q+"%");
    }
    //根据产品名称或者产品id模糊查询，不查询删除的
    //1.查询未分类
    public List<ProductionDetail> queryBypidOrpnameMh2(String q){
        return productionDetilsDAO.queryBypidOrpnameMh2("%"+q+"%");
    }
    //根据产品名称或者产品id模糊查询，不查询删除的
    //1.查询已分类
    public List<ProductionDetail> queryBypidOrpnameMh3(String q, String b){
        return productionDetilsDAO.queryBypidOrpnameMh3("%"+q+"%",b);
    }
    //高级查询（多条件查询）
    public List<ProductionDetail> proHlq(ProductionDetail productionDetail, int currpage, int pagesize){
        Assert.notNull(productionDetail);
        PageRequest pageRequest = new PageRequest(currpage-1,pagesize);
        @SuppressWarnings("unchecked")
        Page<ProductionDetail> result =  productionDetilsDAO.findAll(queryHl(productionDetail),pageRequest);
        List<ProductionDetail> list = result.getContent();
        return list;
    }
    //高级查询（总数）
    public Long proHlqCount(ProductionDetail productionDetail){
        Assert.notNull((productionDetail));
        @SuppressWarnings("unchecked")
        Long count = productionDetilsDAO.count(queryHl(productionDetail));
        return count;
    }

    //高级查询产品信息(添加条件)
    public static Specification<ProductionDetail> queryHl(ProductionDetail productionDetail){
        return new Specification<ProductionDetail>() {
            @Override
            public Predicate toPredicate(Root<ProductionDetail> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //创建条件集合
                List<Predicate> list = new ArrayList<>();
                //添加条件
                if(!StringUtils.isEmpty(productionDetail.getPname())){
                    list.add(criteriaBuilder.like(root.get("pname").as(String.class),"%"+productionDetail.getPname()+"%"));
                }
                if(productionDetail.getPcategory()!=null){
                    list.add(criteriaBuilder.equal(root.get("pcategory").as(Long.class),productionDetail.getPcategory()));
                }
                if(productionDetail.getPprice()!=null){
                    list.add(criteriaBuilder.equal(root.get("pprice").as(Double.class),productionDetail.getPprice()));
                }
                if(productionDetail.getPoprice()!=null){
                    list.add(criteriaBuilder.equal(root.get("poprice").as(Double.class),productionDetail.getPoprice()));
                }
                if(!StringUtils.isEmpty(productionDetail.getPcompany())){
                    list.add(criteriaBuilder.like(root.get("pcompany").as(String.class),"%"+productionDetail.getPcompany()+"%"));
                }
                if(productionDetail.getStartpbirthday()!=null){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("pbirthday").as(Date.class),productionDetail.getStartpbirthday()));
                }
                if(productionDetail.getEndpbirthday()!=null){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("pbirthday").as(Date.class),productionDetail.getEndpbirthday()));
                }
                if(productionDetail.getStartpouttime()!=null){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("pouttime").as(Date.class),productionDetail.getStartpouttime()));
                }
                if(productionDetail.getEndpouttime()!=null){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("pouttime").as(Date.class),productionDetail.getEndpouttime()));
                }
                if(!StringUtils.isEmpty(productionDetail.getPtype())){
                    list.add(criteriaBuilder.equal(root.get("ptype").as(String.class),productionDetail.getPtype()));
                }
                if(!StringUtils.isEmpty(productionDetail.getPspec())){
                    list.add(criteriaBuilder.equal(root.get("pspec").as(String.class),productionDetail.getPspec()));
                }
                if(!StringUtils.isEmpty(productionDetail.getPwunit())){
                    list.add(criteriaBuilder.equal(root.get("pwunit").as(String.class),productionDetail.getPwunit()));
                }
                //产品库存
                if(productionDetail.getStartpstock()!=null){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("pstock").as(Long.class),productionDetail.getStartpstock()));
                }
                if(productionDetail.getEndpstock()!=null){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("pstock").as(Long.class),productionDetail.getEndpstock()));
                }
                list.add(criteriaBuilder.equal(root.get("productionDetailsIsDel").as(String.class),"未删除"));
                Predicate[] predicates = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(predicates));
            }
        };
    }
    /**
     * 模糊查询产品数据
     *
     * @param name
     * @return
     */
    public List<ProductionDetail> fuzzyQueryByProductName(String name) {
        return productionDetilsDAO.fuzzyQueryByProductName("%" + name + "%");
    }

    /**
     * 查询一个产品细节
     *
     * @param id
     * @return
     */
    public ProductionDetail exactQueryProductDetail(Long id) {
        return productionDetilsDAO.findOne(id);
    }

}
